#include <fcntl.h>  
#include <unistd.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include<string.h>
#define BUFFER_SIZE 100

int main()
{
    int fd1, fd2;
    ssize_t bytes_written, bytes_read;
    char buffer[BUFFER_SIZE];

    // 创建并写入file1
    fd1 = open("file1", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd1 == -1)
    {
        perror("Error opening file1");
        exit(EXIT_FAILURE);
    }
    const char *str1 = "abcdefghijklmn";
    bytes_written = write(fd1, str1, strlen(str1));
    if (bytes_written == -1)
    {
        perror("Error writing to file1");
        close(fd1);
        exit(EXIT_FAILURE);
    }
    close(fd1);

    // 创建并写入file2
    fd2 = open("file2", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd2 == -1)
    {
        perror("Error opening file2");
        exit(EXIT_FAILURE);
    }
    const char *str2 = "ABCDEFGHIJKLMN";
    bytes_written = write(fd2, str2, strlen(str2));
    if (bytes_written == -1)
    {
        perror("Error writing to file2");
        close(fd2);
        exit(EXIT_FAILURE);
    }
    // 注意：此时不关闭fd2，因为我们稍后会再次使用它

    // 读取file1的内容
    fd1 = open("file1", O_RDONLY);
    if (fd1 == -1)
    {
        perror("Error opening file1 for reading");
        close(fd2);
        exit(EXIT_FAILURE);
    }
    bytes_read = read(fd1, buffer, BUFFER_SIZE - 1); // 留出空间给'\0'（虽然这里不需要，但为了安全）
    if (bytes_read == -1)
    {
        perror("Error reading from file1");
        close(fd1);
        close(fd2);
        exit(EXIT_FAILURE);
    }
    buffer[bytes_read] = '\0'; // 在这个例子中不是必需的，因为我们知道读取的是固定长度的字符串
    close(fd1);

    // 将读取的内容追加到file2
    // 使用lseek将文件偏移量移动到文件末尾
    off_t offset = lseek(fd2, 0, SEEK_END);
    if (offset == (off_t)-1)
    {
        perror("Error seeking in file2");
        close(fd2);
        exit(EXIT_FAILURE);
    }
    // 写入到file2
    bytes_written = write(fd2, buffer, bytes_read);
    if (bytes_written == -1)
    {
        perror("Error appending to file2");
        close(fd2);
        exit(EXIT_FAILURE);
    }

    // 关闭file2
    close(fd2);

    // 程序成功完成
    return 0;
}
 